#include "dboperator.h"

#include <QMessageBox>
#include <QDebug>
DBOperator::DBOperator(QObject *parent) : QObject(parent)
{
    m_db=QSqlDatabase::addDatabase("QSQLITE");
}

DBOperator &DBOperator::getInstance()
{
    static DBOperator instance;
    return instance;
}

void DBOperator::init()
{
    m_db.setHostName("localhost");
    m_db.setDatabaseName("E:\\develop\\project\\CloudDisk\\TcpServer\\DataBase\\cloud.db");
    if(m_db.open()){
        QSqlQuery query;
        query.exec("select * from userInfo");
        while(query.next()){
            QString data = QString("%1, %2, %3, %4").arg(query.value(0).toString()).arg(query.value(1).toString())
                               .arg(query.value(2).toString()).arg(query.value(3).toString());
            qDebug() << data;
        }
    }
    else {
        QMessageBox::critical(NULL,"打开数据库","打开数据库失败");
    }
}

//用户注册操作
bool DBOperator::handleRegister(const char *name, const char *pwd)
{
    // 考虑极端情况
    if(NULL == name || NULL == pwd)
    {
        return false;
    }
    // 数据插入数据库
    QString strQuery = QString("insert into userInfo(name, pwd) values('%1', '%2')").arg(name).arg(pwd);
    QSqlQuery query;

    // qDebug() << strQuery;
    return query.exec(strQuery); // 数据库中name索引是unique，所以如果name重复会返回false，插入成功返回true
}

//关闭数据库
DBOperator::~DBOperator()
{
    m_db.close();
}
